/**
 * Created by shenaolin on 16/1/18.
 */
$(document).ready(function(){
    $('.page_tab').click(function () {
        $('.page_tab').removeClass('active');
        $(this).addClass('active');

    });

    $('.btn-search').click(function(e) {
        $innerSelect = $('#inner-select');

        var dataType = $innerSelect.attr('data-type');
        var dataId = $innerSelect.attr('data-id');

        var $leaderTableBody = $('.leader_table_body tbody');
        console.log($leaderTableBody);
        if ( dataType == 'school' ) {
            $leaderTableBody.find('tr').show();
        }
        else if ( dataType == 'grade' ) {
            $leaderTableBody.find('tr').hide();
            $leaderTableBody.find('[data-grade="' + dataId + '"]').show();
        }
        else if ( dataType == 'class' ) {
            $leaderTableBody.find('tr').hide();
            $leaderTableBody.find('[data-class="' + dataId + '"]').show();
        }
    });

    var allMyTerms = [];
    var originalTerms = [];
    var schoolID = '';
    var deleteTerms = [];

    $('#save_button').hide();
    $("#edit").hide();
    $("#display_none_message").hide();

    /**
     * 获取leader的信息
     * */
    var leaderInfoReq = new Request('/leader/info');
    leaderInfoReq.getJSON(function(data){
        if (data.successful) {
            schoolID = data.leader.managedSchool.id;
            $('.menu_per').html(data.leader.name);

            getAllTerms(schoolID);
        }
        else {
            alert('获取数据错误！');
        }
    }, function(err){});

    /**
     * 获取所有学期
     * */
    function getAllTerms(schoolID) {
        var termReq = new Request('/school/'+schoolID+'/terms');
        termReq.getJSON(function (data) {
            if (data.data.terms.length != 0) {
                originalTerms = data.data.terms;
                displayOrginalTerms();
            }
            else {
                $("#display_none_message").show();
            }
        }, function (error) {

        });
    }

    function displayOrginalTerms() {
        $('#display').html('');
        if (originalTerms.length != 0) {
            for (var i=0; i<originalTerms.length; i++) {
                $('#display').append(getTermItemDisplayString(originalTerms[i]));
            }
        }
        else {
            $("#display").append('<p style="margin-top: 10px; font-size: 14px; margin-left: 10px; color: darkgray" id="display_none_message">没有学期信息</p>');
        }
    }

    /**
     * 学期设置点编辑
     * */
    $('#edit_button').click(function (event) {
        $("#display").hide();
        $("#edit").show();
        $('#save_button').show();
        $("#edit_button").hide();

        deleteTerms = [];

        var string = '';
        for (var i=0; i<originalTerms.length; i++) {
            string += getTermItemString(originalTerms[i]);
        }
        string += '<div class="leader_pan" id="edit">'+
            '<div class="add-time" id="add_term_button" style="margin-top: 10px; margin-bottom: 10px">'+
            '<i class="iconfont">&#xe60c</i>添加新学期时间'+
            '</div>'+
            '</div>';
        $('#edit').html(string);

        $('.del_btn').click(function (event) {
            deleteButtonClicked(event);
        })

        /**
         * 学期新增按钮点击
         * */
        $("#add_term_button").click(function (event) {
            var myTerm = {
                name: '新学期',
                id: '',
                startTime: '',
                endTime: ''
            }
            $(event.currentTarget).before(getTermItemString(myTerm));
            $('.del_btn').click(function (event) {
                deleteButtonClicked(event);
            })
        });

    });

    /**
     * 学期设置点保存
     * */
    $('#save_button').click(function (event) {

        allMyTerms.splice(0, allMyTerms.length);

        var allItems = $('.hol_lump-item');
        allItems.find('input').removeClass('alert_input');
        for (var i=0; i<allItems.length; i++) {
            var allInputs = $(allItems[i]).find('input');
            if (allInputs.length > 0) {
                var term = {
                    name: allInputs[0].value,
                    startTime: allInputs[1].value,
                    endTime: allInputs[2].value,
                    id: allItems[i].getAttribute('data-id')
                };
                if (!term.name) {
                    $(allInputs[0]).addClass('alert_input');
                    alert('学期名为空！');
                    return;
                }
                if (!term.startTime) {
                    $(allInputs[1]).addClass('alert_input');
                    alert('时间为空！');
                    return;
                }
                if (!term.endTime) {
                    $(allInputs[2]).addClass('alert_input');
                    alert('时间为空！');
                    return;
                }
                if (!timeCheck(term)) {
                    $(allInputs[1]).addClass('alert_input');
                    $(allInputs[2]).addClass('alert_input');
                    alert('时间格式错误！');
                    return;
                }
                var position = isTermDumplicated(term);
                if (position >= 0) {
                    var dInputs = $('.hol_lump-item input');
                    console.log(dInputs);
                    $(dInputs[1+4*position]).addClass('alert_input');
                    $(dInputs[2+4*position]).addClass('alert_input');
                    $(allInputs[1]).addClass('alert_input');
                    $(allInputs[2]).addClass('alert_input');
                    alert('时间有重叠！');
                    return;
                }
                allMyTerms.push(term);
            }
        }
        saveTerms();

        $("#display").show();
        $("#edit").hide();
        $('#save_button').hide();
        $("#edit_button").show();

    });

    function saveTerms() {
        for (var i=0; i<allMyTerms.length; i++) {
            var compare = compareTerm(allMyTerms[i]);
            if (compare == 1) {
                addNewTerm(allMyTerms[i]);
            }
            else if (compare == 0) {
                console.log('should update');
                updateTerm(allMyTerms[i]);
            }
        }
        for (var j=0; j<deleteTerms.length; j++) {
            for (var k=0; k<originalTerms.length; k++) {
                if (originalTerms[k].id == deleteTerms[j]) {
                    deleteTerm(originalTerms[k]);
                    originalTerms.splice(k, 1);
                }
            }
        }
    }

    function isTermDumplicated(myTerm) {
        for (var i=0; i<allMyTerms.length; i++) {
            var term = allMyTerms[i];
            var tStartTime = new Date(term.startTime);
            var tEndTime = new Date(term.endTime);
            var myStartTime = new Date(myTerm.startTime);
            var myEndTime = new Date(myTerm.endTime);
            if ((myStartTime >= tStartTime) && (myStartTime <= tEndTime)) {
                return i;
            }
            if ((myEndTime >= tStartTime) && (myEndTime <= tEndTime)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 新增学期
     * */
    function addNewTerm(term) {
        var req = new Request('/school/'+schoolID+'/terms/add');
        req.postJSON({
            term: term
        }, function (res) {
            if (res.successful) {
                originalTerms.push(res.data.term);
                displayOrginalTerms();
            }
            else {
                alert('更新失败！');
            }
        });
    }

    /**
     * 更新学期
     * */
    function updateTerm(myTerm) {
        console.log(myTerm);
        var req = new Request('/school/'+schoolID+'/terms/update');
        req.postJSON({
            term: myTerm
        }, function (res) {
            if (res.successful) {
                displayOrginalTerms();
            }
            else {
                alert('更新失败！');
            }
        });
    }

    /**
     * 删除学期
     * */
    function deleteTerm(myTerm) {
        console.log(myTerm);
        var req = new Request('/school/'+schoolID+'/terms/remove');
        req.postJSON({
            term: {
                id: myTerm.id
            }
        }, function (res) {
            console.log(res);
            if (res.successful) {
                displayOrginalTerms();
            }
            else {
                alert('更新失败！');
            }
        });
    }

    /**
     * 删除按钮点击
     * */
    function deleteButtonClicked(event) {
        var parentNode = event.currentTarget.parentNode;
        if (parentNode.getAttribute('data-id')) {
            deleteTerms.push(parentNode.getAttribute('data-id'));
        }
        console.log(deleteTerms);
        $(event.currentTarget.parentNode).remove();
    }

    /**
     * 获取每个term展示的item的html string
     * */
    function getTermItemString(myTerm) {
        return '<div class="hol_lump-item" style="margin: 10px auto 5px 10px" data-id="'+ myTerm.id +'">'+
            '<input type="text" value="'+ myTerm.name +'" style="width:70px;height:18px;padding:2px 4px;border: 1px solid #cccccc;font-size: 12px;">'+
            '<form class="sui-form demo8" style="margin-left: 20px;display: inline-block; margin-bottom: 0">'+
            '<input type="text" value="'+dateFormat(myTerm.startTime)+'" data-toggle="datepicker">'+
            '</form>'+
            '&nbsp;&nbsp;至&nbsp;&nbsp;'+
            '<form class="sui-form demo9" style="display: inline-block; margin-bottom: 0">'+
            '<input type="text" value="'+dateFormat(myTerm.endTime)+'" data-toggle="datepicker">'+
            '</form>'+
            '<input type="button" value="删除" class="del_btn" style="background-color: #edf4fe; color: red;">'+
            '</div>';
    }

    function getTermItemDisplayString(myTerm) {
        return '<div class="hol_lump-item" style="margin: 10px auto 5px 10px" data-id="'+ myTerm.id +'">'+
            '<p style="">'+myTerm.name+'<span style="margin-left: 20px">'+dateFormat(myTerm.startTime)+'</span>&nbsp;&nbsp;至&nbsp;&nbsp;'+'<span>'+dateFormat(myTerm.endTime)+'</span>'+'</p>'+
            '</div>';
    }

    /**
     * 对比现在与原有term
     * */
    function compareTerm(myTerm) {
        if (!myTerm.id) {
            return 1;
        }
        for (var i=0; i<originalTerms.length; i++) {
            if (originalTerms[i].id == myTerm.id) {
                if ((originalTerms[i].name == myTerm.name) && (dateFormat(originalTerms[i].startTime) == dateFormat(myTerm.startTime)) && (dateFormat(originalTerms[i].endTime) == dateFormat(myTerm.endTime))) {
                    return 2;
                }
                console.log('update');
                originalTerms[i].name = myTerm.name;
                originalTerms[i].startTime = myTerm.startTime;
                originalTerms[i].endTime = myTerm.endTime;
                return 0;
            }
        }
    }

    function dateFormat(date) {
        if (date) {
            date = new Date(date);
            var month = date.getMonth() + 1;
            if (month < 10) {
                month = '0' + month;
            }
            var day = date.getDate();
            if (day < 10) {
                day = '0' + day;
            }
            return date.getFullYear() + '-' + month + '-' + day;
        }
        return '';
    }

    /**
     * 时间校验
     * */
    function timeCheck(myTerm) {
        var start = new Date(myTerm.startTime);
        var end = new Date(myTerm.endTime);
        if (end > start) {
            return true;
        }
        else {
            return false;
        }
    }

});


function tableDetailButtonClicked(event) {
    var detailButton = event.currentTarget;
    if (detailButton.innerHTML == '返回') {
        $(detailButton).removeClass('table_detail_background');
        $(detailButton).removeClass('table_detail_button_back');
        detailButton.innerHTML = '详细 <i class="iconfont icon-arrow-down attend_table_detail_arrow"></i>';
        var detail_content_id = 'attend_detail_content' + detailButton.getAttribute('data-id');
        var detail_area_id = 'attend_detail_area' + detailButton.getAttribute('data-id');
        $("[data-id="+detail_content_id+"]").animate({
            'height': '0',
            'padding': '0',
            'line-height': '0'
        }, 'fast', function () {
            $("[data-id="+detail_area_id+"]").addClass('table_detail_content_hide');
        });
    }
    else {
        $(detailButton).addClass('table_detail_background');
        $(detailButton).addClass('table_detail_button_back');
        detailButton.innerHTML = '返回';
        var detail_content_id = 'attend_detail_content' + detailButton.getAttribute('data-id');
        var detail_area_id = 'attend_detail_area' + detailButton.getAttribute('data-id');
        $("[data-id="+detail_area_id+"]").removeClass('table_detail_content_hide');
        $("[data-id="+detail_content_id+"]").animate({
            'height': 'auto',
            'padding': '20px 10px 0 10px',
            'line-height': '18px'
        }, 'fast');
    }
}

function innerSelectClicked(event) {
    var $select = $(event.currentTarget);
    var $innerSelect = $('#inner-select');

    var dataType = $select.attr('data-type');
    var dataId = $select.attr('data-id');

    $innerSelect.html($select.html());
    $innerSelect.attr('data-type', dataType);
    $innerSelect.attr('data-id', dataId);
}

var currentValue = '';
var currentGrade = '';
function connectionGradeClicked(event) {
    var currentTarget = event.currentTarget;
    currentValue = $(currentTarget).attr('value');
    if ($(currentTarget).attr('data-id')) {
        currentGrade = $(currentTarget).attr('data-id');
    }
    else {
        currentGrade = '';
    }
    var classes = $("[data-show='class_all']");
    if (currentGrade == '' || !currentGrade) {
        for (var i=0; i<classes.length; i++) {
            myClass = classes[i];
            $(myClass).show();
        }
    }
    else {
        for (var i=0; i<classes.length; i++) {
            var myClass = classes[i];
            if ($(myClass).attr('data-grade') == currentGrade) {
                $(myClass).show();
            }
            else {
                $(myClass).hide();
            }
        }
    }
}
